package cn.crm.spring.shiro;


import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;

import cn.crm.spring.pojo.Right;
import cn.crm.spring.service.IRoleService;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Shiro配置类
 */
@Configuration
public class ShiroConfig {
    // 注入Redis参数，从application.properties获得
    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private Integer port;
    //    @Value("${spring.redis.timeout}")
//    private Integer timeout;
    @Resource
    IRoleService roleService;

    /**
     * 开始Shiro注解（如@RequiresRoles，@RequiresPermissions），
     * 需借助SpringAOP扫描使用Shiro注解的类，并在必要时进行安全逻辑认证
     * 配置以下两个bean（DefaultAdvisorAutoProxyCreator和AuthorizationAttributeSourceAdvisor）
     *
     * @return
     */
//    @Bean
    public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator proxyCreator = new DefaultAdvisorAutoProxyCreator();
        proxyCreator.setProxyTargetClass(true);
        return proxyCreator;
    }

    /**
     * 开启AOP注解
     */
//    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(
            SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor sourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        sourceAdvisor.setSecurityManager(securityManager);
        return sourceAdvisor;
    }

    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        // 使用md5算法进行加密
        credentialsMatcher.setHashAlgorithmName("md5");
        // 设置散列次数：意为加密几次
        credentialsMatcher.setHashIterations(2);
        return credentialsMatcher;
    }

    /**
     * thymeleaf页面上使用shiro标签
     *
     * @return
     */
    @Bean(name = "shiroDialect")
    public ShiroDialect shiroDialect() {
        return new ShiroDialect();
    }

    public RedisManager redisManager() {
        RedisManager redisManager = new RedisManager();
        redisManager.setHost(host);
        redisManager.setPort(port);
//        redisManager.setTimeout(timeout);
        return redisManager;
    }

    public RedisCacheManager cacheManager() {
        RedisCacheManager cacheManager = new RedisCacheManager();
        cacheManager.setRedisManager(redisManager());
        // 缓存名称
        cacheManager.setPrincipalIdFieldName("usrName");//认证身份的对象的属性名
        // 缓存有效时间
        cacheManager.setExpire(1800);
        return cacheManager;
    }

    /**
     * 会话操作
     *
     * @return
     */
    public RedisSessionDAO redisSessionDAO() {
        RedisSessionDAO sessionDAO = new RedisSessionDAO();
        sessionDAO.setRedisManager(redisManager());
        return sessionDAO;
    }

    public DefaultWebSessionManager sessionManager() {
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
        sessionManager.setSessionDAO(redisSessionDAO());
        return sessionManager;
    }

    /**
     * 创建ShiroFilterFactoryBean
     * Shiro过滤器：权限认证
     */
    @Bean("getShiroFilterFactoryBean")
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(
            @Qualifier("getDefaultWebSecurityManager") DefaultWebSecurityManager manager) {
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        // 设置SecurityManager
        factoryBean.setSecurityManager(manager);

        /**
         * Shiro内置过滤器，可以实现权限相关的拦截器
         * 常用的过滤器：
         *      anon：无需认证（登录）可以访问
         *      authc：必须认证才可以访问
         *      user：如果使用rememberMe的功能可以直接访问
         *      perms：该资源必须得到资源权限才可以访问
         *      role：该资源必须得到角色权限才可以访问
         */

        // 权限验证：使用Filter控制资源URL的访问
        factoryBean.setLoginUrl("/index");
        factoryBean.setSuccessUrl("/main");
        factoryBean.setUnauthorizedUrl("/403");//没有权限跳转403页面
        // 必须使用LinkedHashMap（有序集合）
        Map<String, String> map = new LinkedHashMap<>();
        // 配置可以匿名访问的资源URL：静态资源
        map.put("/css/**", "anon");
        map.put("/fonts/**", "anon");
        map.put("/images/**", "anon");
        map.put("/js/**", "anon");
        map.put("/localcss/**", "anon");
        map.put("/localjs/**", "anon");
        // 无需认证
        map.put("/dologin", "anon");
        map.put("/logout", "logout");//注销过滤器，自动注销

        //配置权限验证：特定资源URL必须具备指定的权限才能访问

        //静态
        /*map.put("/user/list","perms[用户列表]");
        map.put("/user/add","perms[用户添加]");
        map.put("/user/edit","perms[用户编辑]");
        map.put("/user/del","perms[用户删除]");*/

        //动态授权
        List<Right> rights = roleService.findAllRights();
        for (Right right : rights) {
            if (right.getRightUrl() != null && !right.getRightUrl().trim().equals("")) {
                map.put(right.getRightUrl(), "perms[" + right.getRightCode() + "]");
            }
        }

        // 配置认证访问：其他资源必须认证通过才能访问
        map.put("/**", "authc");//必须放在过滤器链最后面

//        factoryBean.setFilterChainDefinitionMap(map);

        return factoryBean;
    }


    /**
     * 创建DefaultWebSecurityManager
     * 安全管理器
     */
    @Bean("getDefaultWebSecurityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(
            @Qualifier("getRealm") MyShiroRealm realm) {
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        // 关联Realm
        manager.setRealm(realm);
        // 注入缓存管理器
//        manager.setCacheManager(cacheManager());
        // 注入会话管理器
//        manager.setSessionManager(sessionManager());
        return manager;
    }

    /**
     * 自定义Relam
     */
    @Bean("getRealm")
    public MyShiroRealm getRealm() {
        MyShiroRealm shiroRealm = new MyShiroRealm();
        // 设置启动缓存，并设置缓存名称
//        shiroRealm.setCachingEnabled(true);
//        shiroRealm.setAuthorizationCachingEnabled(true);
//        shiroRealm.setAuthorizationCacheName("authorizationCache");
        // 设置凭证（密码）匹配器
//        shiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return shiroRealm;
    }
}
